package com.csair.seam.controller.mobile;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csair.seam.domain.model.entity.ShareEquip;
import com.csair.seam.domain.model.entity.UserBehavior;
import com.csair.seam.domain.model.enums.UserBehaviorType;
import com.csair.seam.domain.model.enums.VisitsModule;
import com.csair.seam.domain.model.param.ShareEquipParam;
import com.csair.seam.domain.model.vo.ShareEquipModuleVo;
import com.csair.seam.domain.service.ISharingCenterService;
import com.csair.seam.infrastructure.log.VisitsLog;
import com.csair.seam.infrastructure.web.BaseController;
import com.csair.seam.infrastructure.web.BaseResponse;
import com.csair.seam.infrastructure.web.ResponseCode;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

@Api(tags = "共享中心")
@RestController
@RequestMapping("/mobile/sharing")
@Slf4j
public class SharingCenterController extends BaseController{
	
	@Autowired
	@Qualifier("sharingCenterService")
	private ISharingCenterService sharingCenterService;
	
	private List<UserBehavior> getMyFollowBehaviorList() {
		UserBehavior userBehavior = new UserBehavior();
		userBehavior.setUserCode(getAccountForJwt());
		userBehavior.setBehaviorType(UserBehaviorType.FOLLOW.getName());
		List<UserBehavior> myFollowBehaviorList = sharingCenterService.getUserBehaviorList(userBehavior);
		if(CollectionUtils.isEmpty(myFollowBehaviorList)) {
			return Collections.emptyList();
		}
		return myFollowBehaviorList;
	}
	
	
	@GetMapping("/categoryEquipList")
    @ApiOperation(value = "模块展示设备列表", notes = "getCategoryEquipList",httpMethod="GET")
	@VisitsLog(module = VisitsModule.SHARING_CENTER_QUERY)
	public BaseResponse<List<ShareEquipModuleVo>> getCategoryEquipList() {
		ShareEquipParam param = new ShareEquipParam();
		List<ShareEquipModuleVo> moduleShareEquipList = sharingCenterService.findModuleShareEquipList(param);
		List<UserBehavior> myFollowBehaviorList = getMyFollowBehaviorList();
		for (ShareEquipModuleVo shareEquipModuleVo : moduleShareEquipList) {
			for (ShareEquip shareEquip : shareEquipModuleVo.getList()) {
				if(myFollowBehaviorList.stream().anyMatch(e->e.getEquipCode().equals(shareEquip.getCode()))) {
					shareEquip.setFollow("Y");
				}else {
					shareEquip.setFollow("N");
				}
			}
		}
		return buildSuccess(moduleShareEquipList);
	}
	
//	@GetMapping("/more/{categoryId}")
	@GetMapping("/more")
    @ApiOperation(value = "查看更多", notes = "getMoreEquipList",httpMethod="GET")
	public BaseResponse<List<ShareEquip>> getMoreEquipList(@ApiParam ShareEquipParam param) {
//		ShareEquipParam param = new ShareEquipParam();
//		param.setCategoryId(categoryId);
		if(param.getCategoryId() == null) {
			return new BaseResponse<>(ResponseCode.PARAM_ERROR,"参数错误");
		}
		List<ShareEquip> shareEquipList = sharingCenterService.findSharingEquipByParam(param);
		List<UserBehavior> myFollowBehaviorList = getMyFollowBehaviorList();
		for (ShareEquip shareEquip : shareEquipList) {
			if(myFollowBehaviorList.stream().anyMatch(e->e.getEquipCode().equals(shareEquip.getCode()))) {
				shareEquip.setFollow("Y");
			}else {
				shareEquip.setFollow("N");
			}
		}
		return buildSuccess(shareEquipList);
	}
	
	@GetMapping("/recommend")
    @ApiOperation(value = "精选推荐查询", notes = "getRecommendList",httpMethod="GET")
	public BaseResponse<List<ShareEquip>> getRecommendList() {
		List<ShareEquip> recommendEquipList = sharingCenterService.findUserRecommendEquip(getAccountForJwt());
		List<UserBehavior> myFollowBehaviorList = getMyFollowBehaviorList();
		for (ShareEquip shareEquip : recommendEquipList) {
			if(myFollowBehaviorList.stream().anyMatch(e->e.getEquipCode().equals(shareEquip.getCode()))) {
				shareEquip.setFollow("Y");
			}else {
				shareEquip.setFollow("N");
			}
		}
		return buildSuccess(recommendEquipList);
	}
	
	@GetMapping("/detail/{equipCode}")
    @ApiOperation(value = "浏览设备详情", notes = "getEquipByCode",httpMethod="GET")
    public BaseResponse<ShareEquip> getEquipByCode(@PathVariable @ApiParam(value="设备编码",required = true) String equipCode) {
    	ShareEquip equip = sharingCenterService.findShareEquipDetail(equipCode);
    	if(equip == null) {
    		return new BaseResponse<>(ResponseCode.PARAM_ERROR,"没有该设备",null);
    	}
    	
//    	查看用户是否已经关注了此设备
    	UserBehavior userBehavior = new UserBehavior();
    	userBehavior.setUserCode(getAccountForJwt());
    	userBehavior.setEquipCode(equipCode);
    	userBehavior.setBehaviorType(UserBehaviorType.FOLLOW.getName());
    	List<UserBehavior> userBehaviorList = sharingCenterService.getUserBehaviorList(userBehavior);
    	equip.setFollow(CollectionUtils.isEmpty(userBehaviorList)?"N":"Y");
    	
    	//添加浏览记录
		try {
			userBehavior.setBehaviorType(UserBehaviorType.VIEW.getName());
			sharingCenterService.addOrUpdateUserBehavior(userBehavior);
		} catch (Exception e) {
			log.error("添加浏览记录异常", e);
		}
    	return buildSuccess(equip);
    }
	
	@GetMapping("/follow/{equipCode}")
	@ApiOperation(value = "关注设备", notes = "followEquip",httpMethod="GET")
	public BaseResponse<Integer> followEquip(@PathVariable @ApiParam(value="设备编码",required = true) String equipCode) {
		UserBehavior userBehavior = new UserBehavior();
		userBehavior.setUserCode(getAccountForJwt());
		userBehavior.setEquipCode(equipCode);
		userBehavior.setBehaviorType(UserBehaviorType.FOLLOW.getName());
		return buildSuccess(sharingCenterService.addOrUpdateUserBehavior(userBehavior));
	}
	
	@GetMapping("/myfollows")
	@ApiOperation(value = "查询我的关注", notes = "getMyFollows",httpMethod="GET")
	@VisitsLog(module = VisitsModule.SHARING_CENTER_MYFOLLOW)
	public BaseResponse<List<ShareEquip>> getMyFollows() {
		List<UserBehavior> myFollowBehaviorList = getMyFollowBehaviorList();
		if(myFollowBehaviorList.isEmpty()) {
			return buildSuccess(Collections.emptyList());
		}
		List<String> equipCodeList = myFollowBehaviorList.stream().map(UserBehavior::getEquipCode).collect(Collectors.toList());
		ShareEquipParam param = new ShareEquipParam();
		param.setEquipCodeList(equipCodeList);
		List<ShareEquip> myFollowEquipList = sharingCenterService.findSharingEquipByParam(param);
		for (ShareEquip shareEquip : myFollowEquipList) {
			shareEquip.setFollow("Y");
		}
		return buildSuccess(myFollowEquipList);
		
	}
	
	@GetMapping("/cancelFollow/{equipCode}")
	@ApiOperation(value = "取消关注", notes = "cancelFollow",httpMethod="GET")
	public BaseResponse<Integer> cancelFollow(@PathVariable @ApiParam(value="设备编码",required = true) String equipCode) {
		UserBehavior userBehavior = new UserBehavior();
		userBehavior.setUserCode(getAccountForJwt());
		userBehavior.setEquipCode(equipCode);
		userBehavior.setBehaviorType(UserBehaviorType.FOLLOW.getName());
		return buildSuccess(sharingCenterService.delUserBehavior(userBehavior));
	}
	
	@GetMapping("/mytracks")
	@ApiOperation(value = "查询我的足迹", notes = "getMyTracks",httpMethod="GET")
	public BaseResponse<List<ShareEquip>> getMyTracks() {
		UserBehavior userBehavior = new UserBehavior();
		userBehavior.setUserCode(getAccountForJwt());
		userBehavior.setBehaviorType(UserBehaviorType.VIEW.getName());
		List<UserBehavior> myViewList = sharingCenterService.getUserBehaviorList(userBehavior);
		if(CollectionUtils.isEmpty(myViewList)) {
			return buildSuccess(Collections.emptyList());
		}
		List<String> equipCodeList = myViewList.stream().map(UserBehavior::getEquipCode).collect(Collectors.toList());
		ShareEquipParam param = new ShareEquipParam();
		param.setEquipCodeList(equipCodeList);
		return buildSuccess(sharingCenterService.findSharingEquipByParam(param));
	}
	
	@GetMapping("/deltrack/{equipCode}")
	@ApiOperation(value = "删除足迹", notes = "delTrack",httpMethod="GET")
	public BaseResponse<Integer> delTrack(@PathVariable @ApiParam(value="设备编码",required = true) String equipCode) {
		UserBehavior userBehavior = new UserBehavior();
		userBehavior.setUserCode(getAccountForJwt());
		userBehavior.setEquipCode(equipCode);
		userBehavior.setBehaviorType(UserBehaviorType.VIEW.getName());
		return buildSuccess(sharingCenterService.delUserBehavior(userBehavior));
	}
	
	@GetMapping("/cleartrack")
	@ApiOperation(value = "清空足迹", notes = "clearTrack",httpMethod="GET")
	public BaseResponse<Integer> clearTrack() {
		UserBehavior userBehavior = new UserBehavior();
		userBehavior.setUserCode(getAccountForJwt());
		userBehavior.setBehaviorType(UserBehaviorType.VIEW.getName());
		return buildSuccess(sharingCenterService.delUserBehavior(userBehavior));
	}
	
	@GetMapping("/search")
	@ApiOperation(value = "搜索设备", notes = "searchEquip",httpMethod="GET")
	public BaseResponse<List<ShareEquip>> searchEquip(@RequestParam String keyword) {
		try {
			//添加搜索记录
			UserBehavior userBehavior = new UserBehavior();
			userBehavior.setUserCode(getAccountForJwt());
			userBehavior.setKeyword(keyword);
			userBehavior.setBehaviorType(UserBehaviorType.SEARCH.getName());
			sharingCenterService.addOrUpdateUserBehavior(userBehavior);
		} catch (Exception e) {
			log.error("添加搜索记录异常",e);
		}
		
		//搜索设备
		ShareEquipParam param = new ShareEquipParam();
		param.setKeyword(keyword);
		
		List<ShareEquip> shareEquipList = sharingCenterService.findSharingEquipByParam(param);
		List<UserBehavior> myFollowBehaviorList = getMyFollowBehaviorList();
		for (ShareEquip shareEquip : shareEquipList) {
			if(myFollowBehaviorList.stream().anyMatch(e->e.getEquipCode().equals(shareEquip.getCode()))) {
				shareEquip.setFollow("Y");
			}else {
				shareEquip.setFollow("N");
			}
		}
		return buildSuccess(shareEquipList);
	}
	
	@GetMapping("/searchHistory")
	@ApiOperation(value = "查询搜索历史", notes = "getMySearch",httpMethod="GET")
	public BaseResponse<List<UserBehavior>> getSearchHistory() {
		UserBehavior userBehavior = new UserBehavior();
		userBehavior.setUserCode(getAccountForJwt());
		userBehavior.setBehaviorType(UserBehaviorType.SEARCH.getName());
		return buildSuccess(sharingCenterService.getUserBehaviorList(userBehavior));
	}
	
	@GetMapping("/delSearch")
	@ApiOperation(value = "删除某个搜索历史", notes = "delSearch",httpMethod="GET")
	public BaseResponse<Integer> delSearch(@RequestParam String keyword) {
		UserBehavior userBehavior = new UserBehavior();
		userBehavior.setUserCode(getAccountForJwt());
		userBehavior.setBehaviorType(UserBehaviorType.SEARCH.getName());
		userBehavior.setKeyword(keyword);
		return buildSuccess(sharingCenterService.delUserBehavior(userBehavior));
	}
	
	@GetMapping("/clearSearch")
	@ApiOperation(value = "清空搜索历史", notes = "clearSearch",httpMethod="GET")
	public BaseResponse<Integer> clearSearch() {
		UserBehavior userBehavior = new UserBehavior();
		userBehavior.setUserCode(getAccountForJwt());
		userBehavior.setBehaviorType(UserBehaviorType.SEARCH.getName());
		return buildSuccess(sharingCenterService.delUserBehavior(userBehavior));
	}
	
	@GetMapping("/company")
	@ApiOperation(value = "查询本单位共享的设备", notes = "getEquipListForCurOrg",httpMethod="GET")
	public BaseResponse<List<ShareEquip>> getEquipListForCurOrg() {
		List<ShareEquip> shareEquipList = sharingCenterService.findMyOrgShareEquipList(getAccountForJwt());
		List<UserBehavior> myFollowBehaviorList = getMyFollowBehaviorList();
		for (ShareEquip shareEquip : shareEquipList) {
			if(myFollowBehaviorList.stream().anyMatch(e->e.getEquipCode().equals(shareEquip.getCode()))) {
				shareEquip.setFollow("Y");
			}else {
				shareEquip.setFollow("N");
			}
		}
		return buildSuccess(shareEquipList);
	}
	
	@GetMapping("/myUnit")
	@ApiOperation(value = "查询本单位共享的设备（分页）", notes = "getEquipPageForCurOrg",httpMethod="GET")
	public BaseResponse<IPage<ShareEquip>> getEquipPageForCurOrg(@ApiParam(value = "查询参数")ShareEquipParam param) {
		Page<ShareEquip> shareEquipPage = sharingCenterService.findMyOrgShareEquipPage(param,getAccountForJwt());
		List<UserBehavior> myFollowBehaviorList = getMyFollowBehaviorList();
		for (ShareEquip shareEquip : shareEquipPage.getRecords()) {
			if(myFollowBehaviorList.stream().anyMatch(e->e.getEquipCode().equals(shareEquip.getCode()))) {
				shareEquip.setFollow("Y");
			}else {
				shareEquip.setFollow("N");
			}
		}
		return buildSuccess(shareEquipPage);
	}
	
	@GetMapping("/thumb/{equipCode}")
    @ApiOperation(value = "获取设备缩略图", notes = "getEquipThumbByCode",httpMethod="GET")
    public BaseResponse<byte[]> getEquipThumbByCode(@PathVariable @ApiParam(value="设备编码",required = true) String equipCode) {
    	ShareEquip equip = sharingCenterService.findShareEquipThumb(equipCode);
    	if(equip == null) {
    		return buildSuccess(null); 
    	}
    	return buildSuccess(equip.getPreViewImage()); 
    }
}
